<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\deerhome\CardItems;
use app\admin\model\deerhome\ItemsGg;
/**
 * 套餐次卡
 *
 * @icon fa fa-circle-o
 */
class Card extends Backend
{

    /**
     * Card模型对象
     * @var \app\admin\model\deerhome\Card
     */
    protected $model = null;
    protected $multiFields = 'status,is_home,vip_discount,item_show';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Card;
        $this->view->assign("yesNoList", $this->model->getYesNoList());
        $this->view->assign("angetList", $this->model->getAngetList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("timeArea", $this->model->getTimeAreaList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['cardItems'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if($params['name']==""){
            $this->error("套餐名称不能为空");
        }
        if($params['card_item']=="[]"){
            $this->error("请选择套餐内产品");
        }
        $params['price']=floatval($params['price']);
        if($params['price']<=0){
            $this->error("套餐售价必须大于0");
        }
        $isExit=$this->model->where('name',$params['name'])->find();
        if($isExit){
            $this->error("套餐名称已存在");
        }
        $car_items=json_decode($params['card_item'],true);
        if(count($car_items)<=0){
            $this->error("请选择套餐内产品");
        }
        $err="";
        foreach($car_items as $k=>&$v){
            $times=0;
            foreach($car_items as $kk=>$vv){
                if($v['hash']==$vv['hash']){
                    $times++;
                }
                if($times>1){
                    $err="套餐内产品【{$vv['name']}】下的规格【{$vv['gg']}】重复，请检查！";
                    break;
                }
            }
            if($v['num']<=0){
                $err="套餐内产品次数必须大于0，请检查！";
            }
            if($v['price']<=0){
                $err="套餐内单价必须大于0，请检查！";
            }
            $v['deerhome_items_id']=ItemsGg::where('hash',$v['hash'])->value('jz_items_id');
            if(!$v['deerhome_items_id']){
                $err="套餐内产品【{$v['name']}】下的规格【{$v['gg']}】不存在，请检查！";
            }
        }
        if($err){
            $this->error($err);
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->save($params);
            $arr=[];
            foreach($car_items as $k3=>$v3){
                $arr[$k3]['deerhome_card_id']=$this->model->id;
                $arr[$k3]['deerhome_items_id']=$v3['deerhome_items_id'];
                $arr[$k3]['deerhome_items_gg_hash']=$v3['hash'];
                $arr[$k3]['num']=$v3['num'];
                $arr[$k3]['price']=$v3['price'];
            }
            (new CardItems)->allowField(true)->saveAll($arr);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $card_item_res=[];
            $card_item=$row->cardItems()->select();
            foreach($card_item as $k=>$v){
                $v=$v->toArray();
                $arr=[];
                $arr['id']=$v['id'];
                $arr['hash']=$v['deerhome_items_gg_hash'];
                $arr['gg']=$v['items_gg_name'];
                $arr['name']=$v['items_name'];
                $arr['dw']=$v['items_gg_dw'];
                $arr['price']=$v['price'];
                $arr['price_market']=$v['items_gg_price'];
                $arr['num']=$v['num'];
                array_push($card_item_res,$arr);
            }
            $row['card_item']=json_encode($card_item_res);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($params['name']==""){
            $this->error("套餐名称不能为空");
        }
        if($params['card_item']=="[]"){
            $this->error("请选择套餐内产品");
        }
        $params['price']=floatval($params['price']);
        if($params['price']<=0){
            $this->error("套餐售价必须大于0");
        }
        $isExit=$this->model->where('name',$params['name'])->where('id','<>',$row['id'])->find();
        if($isExit){
            $this->error("套餐名称已存在");
        }
        $car_items=json_decode($params['card_item'],true);
        if(count($car_items)<=0){
            $this->error("请选择套餐内产品");
        }
        $err="";
        foreach($car_items as $k=>&$v){
            $times=0;
            foreach($car_items as $kk=>$vv){
                if($v['hash']==$vv['hash']){
                    $times++;
                }
                if($times>1){
                    $err="套餐内产品【{$vv['name']}】下的规格【{$vv['gg']}】重复，请检查！";
                    break;
                }
            }
            if($v['num']<=0){
                $err="套餐内产品次数必须大于0，请检查！";
            }
            if($v['price']<=0){
                $err="套餐内单价必须大于0，请检查！";
            }
            $v['deerhome_items_id']=ItemsGg::where('hash',$v['hash'])->value('jz_items_id');
            if(!$v['deerhome_items_id']){
                $err="套餐内产品【{$v['name']}】下的规格【{$v['gg']}】不存在，请检查！";
            }
        }
        if($err){
            $this->error($err);
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            CardItems::where('deerhome_card_id',$row->id)->delete();
            $arr=[];
            foreach($car_items as $k3=>$v3){
                $arr[$k3]['deerhome_card_id']=$row->id;
                $arr[$k3]['deerhome_items_id']=$v3['deerhome_items_id'];
                $arr[$k3]['deerhome_items_gg_hash']=$v3['hash'];
                $arr[$k3]['num']=$v3['num'];
                $arr[$k3]['price']=$v3['price'];
            }
            (new CardItems)->allowField(true)->saveAll($arr);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
